package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.Product;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * 商品控制器
 */
@RestController
@RequestMapping("/api/products")
@CrossOrigin(origins = "*")
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    /**
     * 获取商品列表（分页）
     */
    @GetMapping
    public Result<Page<Product>> getProducts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sortBy,
            @RequestParam(defaultValue = "asc") String sortDir) {
        
        Sort sort = sortDir.equalsIgnoreCase("desc") ? 
            Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
        Pageable pageable = PageRequest.of(page, size, sort);
        
        Page<Product> products = productService.findAll(pageable);
        return Result.success(products);
    }
    
    /**
     * 根据ID获取商品
     */
    @GetMapping("/{id}")
    public Result<Product> getProduct(@PathVariable Long id) {
        Optional<Product> product = productService.findById(id);
        return product.map(Result::success).orElse(Result.notFound());
    }
    
    /**
     * 根据商品编码获取商品
     */
    @GetMapping("/code/{productCode}")
    public Result<Product> getProductByCode(@PathVariable String productCode) {
        Optional<Product> product = productService.findByProductCode(productCode);
        return product.map(Result::success).orElse(Result.notFound());
    }
    
    /**
     * 根据条码获取商品
     */
    @GetMapping("/barcode/{barcode}")
    public Result<Product> getProductByBarcode(@PathVariable String barcode) {
        Optional<Product> product = productService.findByBarcode(barcode);
        return product.map(Result::success).orElse(Result.notFound());
    }
    
    /**
     * 搜索商品
     */
    @GetMapping("/search")
    public Result<Page<Product>> searchProducts(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Product> products = productService.findByKeyword(keyword, pageable);
        return Result.success(products);
    }
    
    /**
     * 根据分类获取商品
     */
    @GetMapping("/category/{categoryId}")
    public Result<List<Product>> getProductsByCategory(@PathVariable Long categoryId) {
        List<Product> products = productService.findByCategoryId(categoryId);
        return Result.success(products);
    }
    
    /**
     * 根据品牌获取商品
     */
    @GetMapping("/brand/{brand}")
    public Result<List<Product>> getProductsByBrand(@PathVariable String brand) {
        List<Product> products = productService.findByBrand(brand);
        return Result.success(products);
    }
    
    /**
     * 创建商品
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public Result<Product> createProduct(@Valid @RequestBody Product product) {
        // 检查商品编码是否已存在
        if (productService.existsByProductCode(product.getProductCode())) {
            return Result.error("商品编码已存在");
        }
        
        // 检查条码是否已存在
        if (product.getBarcode() != null && productService.existsByBarcode(product.getBarcode())) {
            return Result.error("条码已存在");
        }
        
        Product savedProduct = productService.save(product);
        return Result.success("商品创建成功", savedProduct);
    }
    
    /**
     * 更新商品
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public Result<Product> updateProduct(@PathVariable Long id, @Valid @RequestBody Product product) {
        Optional<Product> existingProduct = productService.findById(id);
        if (!existingProduct.isPresent()) {
            return Result.notFound();
        }
        
        product.setId(id);
        Product updatedProduct = productService.update(product);
        return Result.success("商品更新成功", updatedProduct);
    }
    
    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> deleteProduct(@PathVariable Long id) {
        Optional<Product> product = productService.findById(id);
        if (!product.isPresent()) {
            return Result.notFound();
        }
        
        productService.deleteById(id);
        return Result.success("商品删除成功");
    }
}
